package com.bsoft.client.transport;

import com.bsoft.core.common.RpcResponse;
import com.bsoft.core.protocol.MessageProtocol;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 由于netty消息通信都是异步的，因此我们需要把所有未处理的future全部缓存起来
 */
public class UnsolvedResponseCache {
    // 利用CompletableFuture特性，实现缓存异步响应结果
    private static Map<String, CompletableFuture<MessageProtocol<RpcResponse>>> responseCacheMap = new ConcurrentHashMap<>();


    public static void put(String requestId, CompletableFuture<MessageProtocol<RpcResponse>> future) {
        responseCacheMap.put(requestId, future);
    }

    /**
     * 完成之后，缓存清除即可
     *
     * @param protocol
     */
    public static void complete(MessageProtocol<RpcResponse> protocol) {
        // 清除缓存
        CompletableFuture<MessageProtocol<RpcResponse>> future = responseCacheMap.remove(protocol.getHeader().getRequestId());
        if (future != null) {
            // 完成后，get方法才能获取信息（解锁操作）
            future.complete(protocol);
        }else {
            throw new IllegalStateException("未识别的future");
        }
    }
}
